import 'package:fish_redux/fish_redux.dart';
import 'package:azlistview/azlistview.dart';
import '../../../app_files.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'action.dart';
import 'state.dart';

Effect<StaffLoginViewState> buildEffect() {
  return combineEffects(<Object, Effect<StaffLoginViewState>>{
    Lifecycle.initState: _initState,
    StaffLoginViewAction.onSubmit: _onSubmit,
    StaffLoginViewAction.onTapRole: _onTapRole,
  });
}

void _initState(Action action, Context<StaffLoginViewState> ctx) async {
  if (ctx.state.roleController.text.isNotEmpty)
    GlobalStore.store.getState().userInfo.currentRoleName =
        ctx.state.roleController.text;
}

void _onTapRole(Action action, Context<StaffLoginViewState> ctx) async {
  await CommonUtils.pushRoute(ctx.context, RoutePath.userTypeView);
  if (GlobalStore.store.getState().userInfo.currentRoleName.isNotEmpty)
    ctx.state.roleController.text =
        GlobalStore.store.getState().userInfo.currentRoleName;
  ctx.dispatch(StaffLoginViewActionCreator.onAction());
}

void _onSubmit(Action action, Context<StaffLoginViewState> ctx) async {
  print(GlobalStore.store.getState().userInfo.currentRoleName);
  if (GlobalStore.store.getState().userInfo.currentRoleName.isEmpty) {
    CommonUtils.showErrorInfo(ctx.context, '请选择您的角色');
    return;
  }

  if (ctx.state.phoneController.text.length == 0) {
    CommonUtils.showErrorInfo(ctx.context, '请输入您的登录账号');
    return;
  }
  if (ctx.state.passwordController.text.length == 0) {
    CommonUtils.showErrorInfo(ctx.context, '请输入您的密码');
    return;
  }

  CommonUtils.showWaitLoading(ctx.context);
  String roleName = GlobalStore.store.getState().userInfo.currentRoleName;
  ResultData res = await CommonNetWork.staffUserLogin(
    ctx.state.phoneController.text,
    ctx.state.passwordController.text,
    roleName,
  );
  Navigator.pop(ctx.context);
  if (res.success) {
    CommonUtils.setStaffLoginDefaultInfo(
        account: ctx.state.phoneController.text,
        password: ctx.state.passwordController.text,
        roleName: roleName);
    UserInfoEntity info = UserInfoEntity.fromStaffJson(res.data);
    await CommonUtils.initImageConfig(token: info.token, isGasUser: false);
    info.currentRoleName = roleName;
    info.password = ctx.state.passwordController.text;
    info.mobile = ctx.state.phoneController.text;
    info.isGsUser = false;
    if (info.isCheckWorker) {
      SharedPreferences preferences = await SharedPreferences.getInstance();
      int currentPlan =
          preferences.getInt(UserInfoConst.currentPlan + info.userid) ?? 0;
      info.currentPlan = currentPlan;
      CommonUtils.showWaitLoading(ctx.context);
      ResultData plans = await CommonNetWork.staffCheckPlans(token: info.token);
      Navigator.pop(ctx.context);
      if (plans.success) {
        List list = plans.data['data'];
        info.plans =
            list.map<PlanItemModel>((e) => PlanItemModel.fromJson(e)).toList();
        SuspensionUtil.sortListBySuspensionTag(info.plans);
      } else {
        CommonUtils.showErrorInfo(ctx.context, res.desc);
      }
    }

    if (info.isPatrolWorker) {
      SharedPreferences preferences = await SharedPreferences.getInstance();
      int currentPlan =
          preferences.getInt(UserInfoConst.currentPatrolPlan + info.userid) ??
              0;
      info.currentPatrolPlan = currentPlan;
      ResultData plans =
          await CommonNetWork.staffPatrolPlans(token: info.token);
      if (plans.success) {
        List list = plans.data['data'];
        List<PatrolPlanModel> patrolPlans = list
            .map<PatrolPlanModel>((e) => PatrolPlanModel.fromJson(e))
            .toList();
        SuspensionUtil.sortListBySuspensionTag(patrolPlans);
        info.patrolPlans = patrolPlans;
      }
    }
    GlobalStore.store.dispatch(GlobalActionCreator.onUserLogin(info));
    bus.emit('refreshMain');
    Navigator.popUntil(ctx.context, ModalRoute.withName('/'));
  } else {
    CommonUtils.showErrorInfo(ctx.context, res.desc);
  }
}
